package kr.saeildamil.androidstudy_second.multimedia;

import kr.saeildamil.androidstudy_second.R;
import android.app.Activity;
import android.content.ContentResolver;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.provider.MediaStore.Images;
import android.provider.MediaStore.MediaColumns;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;

public class ImageViewer extends Activity {
	ImageView mImage;
	Cursor mCursor;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.ch33_imageviewer);

		ListView list = (ListView) findViewById(R.id.list);
		mImage = (ImageView) findViewById(R.id.image);

		ContentResolver cr = getContentResolver();
		mCursor = cr.query(Images.Media.EXTERNAL_CONTENT_URI, null, null, null,
				null);
		SimpleCursorAdapter Adapter = new SimpleCursorAdapter(this,
				android.R.layout.simple_list_item_1, mCursor,
				new String[] { MediaColumns.DISPLAY_NAME },
				new int[] { android.R.id.text1 });
		list.setAdapter(Adapter);
		list.setOnItemClickListener(mItemClickListener);
		startManagingCursor(mCursor);
	}

	AdapterView.OnItemClickListener mItemClickListener = new AdapterView.OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
			mCursor.moveToPosition(position);
			String path = mCursor.getString(mCursor
					.getColumnIndex(Images.ImageColumns.DATA));
			try {
				BitmapFactory.Options opt = new BitmapFactory.Options();
				opt.inSampleSize = 4;
				Bitmap bm = BitmapFactory.decodeFile(path, opt);
				mImage.setImageBitmap(bm);
			} catch (OutOfMemoryError e) {
				Toast.makeText(ImageViewer.this, "이미지가 너무 큽니다", 0).show();
			}
		}
	};
}
